package canraid.gui;

import java.util.Set;

import canraid.debug.Level;
import canraid.debug.Logger;
import canraid.gen.R;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class BluetoothList extends Activity {

    public static String DEVICE_ADDRESS  = "device_address";

    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.setLog((Object)this,Level.ASSERT,"onCreate().");

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.bluetooth_list);
        setResult(Activity.RESULT_CANCELED);

        Button scanButton = (Button) findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                doDiscovery();
                v.setVisibility(View.GONE);
            }
        });
        Logger.setLog((Object)this,Level.INFO,"onCreate(). --> step 1 OK.");

        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, canraid.gen.R.layout.device_name);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, canraid.gen.R.layout.device_name);
        

        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);

        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);
        Logger.setLog((Object)this,Level.INFO,"onCreate(). --> step 2 OK.");

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            String noDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
        Logger.setLog((Object)this,Level.INFO,"onCreate(). --> step 3 OK. onCreate finished.");
    }

    protected void onDestroy() {
        Logger.setLog((Object)this,Level.ASSERT,"onDestroy().");

        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        this.unregisterReceiver(mReceiver);
        
        super.onDestroy();
    }

    private void doDiscovery() {
    	Logger.setLog((Object)this,Level.ASSERT,"doDiscovery().");
    	
        setProgressBarIndeterminateVisibility(true);
        setTitle(R.string.scanning);
        Logger.setLog((Object)this,Level.INFO,"doDiscovery(). --> step 1 OK.");

        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

        if (mBtAdapter.isDiscovering()) {
        	Logger.setLog((Object)this,Level.INFO,"doDiscovery(). Stop Discovering.");
            mBtAdapter.cancelDiscovery();
        }
        Logger.setLog((Object)this,Level.INFO,"doDiscovery(). Discovering...");
        try{
        	mBtAdapter.startDiscovery();
        }
        catch(Exception e){
        	Logger.setLog((Object)this,Level.ERROR,"doDiscovery(). ERROR:"+e.getMessage());
        	return;
        }
        Logger.setLog((Object)this,Level.INFO,"doDiscovery(). --> step 2 OK. doDiscovery finished");
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        	Logger.setLog((Object)this,Level.ASSERT,"onItemClick().");
        	
            mBtAdapter.cancelDiscovery();
            
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            Intent intent = new Intent();
            intent.putExtra(DEVICE_ADDRESS, address);

            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
        	Logger.setLog((Object)this,Level.ASSERT,"onReceive().");
        	
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };
}
